const React = require('react');

const { renderToString, renderToStaticMarkup } = require('react-dom/server');
/**
 Render a React element to its initial HTML. React will return an HTML string.
 You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.

 If you call ReactDOM.hydrate() on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
*/

const http = require('http');


//组件
class Index extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    //TODO 这是jsx语法,需要进行编译,emmm... 我们这里为了演示renderToString方法,直接手动调用babel命令编译了一下 参看README.md
    return <h1>hello react ssr!</h1>
  }
}


//服务
http.createServer((req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/html'
    });

    // const html = renderToString(<Index/>);
    // ↕ 如果只是单纯的html渲染 此时上下是等价的
    const html = renderToStaticMarkup(<Index/>);

    res.end(`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React SSR</title>
</head>
<body>
    <div id="root">
       ${html}
    </div>
</body>
</html>`);

  }
).listen(9001);

console.log('server start. 9001');
